package com.example.carrierapp.net;

import android.util.Log;

import com.example.carrierapp.common.CarrierApplication;
import com.example.carrierapp.config.ConstValue;
import com.example.carrierapp.util.SPUtils;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/3/30.
 */
public class AppClient {
//        public static final String BASE_URL = "http://221.237.162.142:11087/";//外网测试多次任务分支
//    public static final String BASE_URL = "http://10.130.0.128:13003/";// 内网测试多次任务分支
    private static final String BASE_URL = "http://10.130.0.128:10020/";// 内网测试多次任务分支
//    public static final String BASE_URL = "http://10.6.74.144:80/";// 内网测试多次任务分支
//        public static final String BASE_URL = "http://api56.jwell56.com/";//正式环境
    private static Retrofit retrofit;
    /**
     * 请求头必须添加的一个KEY，用于确定用户是否别处登录
     */
    private static final String URL_ADDRESS_HEARD_KEY = "Authorization";
    /**
     * 请求头必须添加的一个KEY对应的VALUE值，用于确定用户是否别处登录
     */
    private static final String URL_ADDRESS_HEARD_VALUE = "Bearer ";
    //log拦截器
    private static Interceptor loggingInterceptor = new HttpLoggingInterceptor(message -> Log.i("OkHttpLog", "OkHttp====Message:" + message)).setLevel(HttpLoggingInterceptor.Level.BODY);
    private static Interceptor interceptor = chain -> {
        //获取request
        Request request = chain.request();
        //获取request的创建者builder
        Request.Builder builder = request.newBuilder();
        //从request中获取headers，通过给定的键url_name
        List<String> headerValuesS = request.headers("url_name");
        if (headerValuesS != null && headerValuesS.size() > 0) {
            //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
            builder.removeHeader("url_name");
            //匹配获得新的BaseUrl
            String headerValue = headerValuesS.get(0);
            HttpUrl newBaseUrl = HttpUrl.parse(BASE_URL);
            //从request中获取原有的HttpUrl实例oldHttpUrl
            HttpUrl oldHttpUrl = request.url();
            //重建新的HttpUrl，修改需要修改的url部分
            HttpUrl newFullUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl.scheme())
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port())
                    .build();

            //重建这个request，通过builder.url(newFullUrl).build()；
            //然后返回一个response至此结束修改
            return chain.proceed(builder.url(newFullUrl).build());
        } else {
            return chain.proceed(request);
        }
    };

    public Retrofit getRetrofit() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(1000 * 10, TimeUnit.SECONDS);
        //OkHttp进行添加拦截器loggingInterceptor
        builder.addInterceptor(loggingInterceptor);
        builder.addInterceptor(interceptor);
        Interceptor requestInterceptor = chain -> {
            Request request = chain.request();
            String key = SPUtils.getString(CarrierApplication.mAppContext, ConstValue.URL_TOKEN, "");
            Request compressedRequest;
            if (key != null && !key.isEmpty()) {
                compressedRequest = request.newBuilder()
                        .header("Accept-Language", Locale.getDefault().toString())
                        .header("Accept-Charset", "UTF-8")
                        .header("Connection", "Keep-Alive")
                        .addHeader(URL_ADDRESS_HEARD_KEY, URL_ADDRESS_HEARD_VALUE + key)
                        .build();
            } else {
                compressedRequest = request.newBuilder()
                        .header("Accept-Language", Locale.getDefault().toString())
                        .header("Accept-Charset", "UTF-8")
                        .header("Connection", "Keep-Alive")
                        .build();
            }
            Log.i("TAG", "Token值为-------" + key);
            Response response = chain.proceed(compressedRequest);
            return response;
        };
        builder.interceptors().add(requestInterceptor);

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(builder.build())
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }

    private AppClient() {
    }

    public static AppClient getInstance() {
        return AppClientHolder.APP_CLIENT;
    }

    private static class AppClientHolder {
        private static final AppClient APP_CLIENT = new AppClient();
    }
}
